// pages/share/share.js
const app = getApp();
import {
  share,
  getPoster
} from '../../../../config/https.js';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    showit: true, // 是否显示
    show: false, // 显示分享弹窗？
    buynum: 0, // 下单人数
    invitenum: 0, // 邀请人数
    rules: null, // 规则
    posterUrl: null, // 绘制完成的海报
    imgURL: '', // 分享海报的商品图片
    share_bg: '', // 分享背景图
    tabs: [],
    current: 0,
    noramalData: [],
    show: false,
  },
  twoTab(e) {
    this.setData({
      current: e.currentTarget.dataset.index,
      noramalData: this.data.tabs[e.currentTarget.dataset.index].article
    })
    this.isVideo()
    this.selectComponent("#list").selectTab(e);
  },
  onMyEvent(e) {
    console.log(e)
    this.setData({
      current: e.detail,
      noramalData: this.data.tabs[e.detail].article
    })
    this.isVideo()
  },
  all() {
    this.setData({
      show: !this.data.show
    })
  },
  onLoad: function (options) {
    this.init()
    // this.getData();
    // this.setData({
    //   userInfo: JSON.parse(wx.getStorageSync('userInfos'))
    // })
    // let that = this;
    // wx.getImageInfo({
    //   src: JSON.parse(wx.getStorageSync('userInfos')).avatar,
    //   success(data) {
    //     that.setData({
    //       userImg: data.path,
    //     })
    //   }
    // })
  },
  isVideo() {
    if (this.data.noramalData.length > 0) {
      let arr = this.data.noramalData
      // let reg = /\.[^\.]+$/g
      arr.forEach((item) => {
        // let str = reg.exec(item.image)
        let arr1 = item.image.split('').reverse()
        let str = arr1.slice(0,4).reverse().join('')
        console.log(str)
        if (str != null&&str != '.jpg' && str != '.png' && str && '.jpeg' && str != '.gif' && str != '.bmp') {
          item.isVideo = 1
        } else {
          item.isVideo = 0
        }
      })
      this.setData({
        noramalData: arr
      })
      console.log(this.data.noramalData)
    }
  },
  init() {
    app.loading();
    let than = this
    wx.request({
      url: app.baseURL + 'article/anli',
      data: {
        token: wx.getStorageSync('userId') ? wx.getStorageSync('userId') : ''
      },
      success: res => {
        let data = res.data;
        wx.hideLoading();
        if (data.code == 1) {
          than.setData({
            tabs: data.data,
            noramalData: data.data[0].article
          })
          than.isVideo()
        } else {
          app.$tip(data.msg);
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onShow: function () {

  },

  onReady() {},

  // 获取数据
  getData() {
    app.loading();
    let that = this;
    share({
      token: wx.getStorageSync('userId')
    }).then(res => {
      wx.hideLoading();
      wx.stopPullDownRefresh();
      if (res.code == 1) {
        this.setData({
          showit: true,
          share_bg: res.data.share_background_picture,
          buynum: res.data.order,
          invitenum: res.data.subordinate,
        })

        if (res.data.share_poster) {
          wx.getImageInfo({
            src: res.data.share_poster,
            success(data) {
              that.setData({
                imgURL: data.path
              })
            }
          })
        }
      } else {
        this.setData({
          showit: true
        })
        app.$tip(res.msg)
      }
    })
  },

  // 分享按钮
  share() {
    if (!this.data.posterUrl) {
      this.getShare();
    } else {
      this.setData({
        show: true
      })
    }

  },

  // 关闭分享
  closed() {
    this.setData({
      show: false
    })
  },

  // 获取海报
  getShare() {
    let that = this;
    app.loading();
    getPoster({
      token: wx.getStorageSync('userId'),
    }).then(res => {
      // 获取成功
      if (res.code == 1) {
        wx.getImageInfo({
          src: res.data,
          success(das) {
            if (das.path && that.data.userImg) {
              let ctx = wx.createCanvasContext('myCanvas');
              // 设置商品图片
              ctx.drawImage(that.data.imgURL, 0, 0, Math.floor(270), Math.floor(388))
              ctx.setFillStyle('white');
              ctx.fillRect(0, Math.floor(388), Math.floor(270), Math.floor(80));
              // 设置用户头像
              ctx.drawImage(that.data.userImg, Math.floor(196), Math.floor(395), 66, 66)
              // 设置小程序码
              ctx.drawImage(das.path, Math.floor(8), Math.floor(395), 66, 66)
              // 设置扫码提示图片
              ctx.drawImage('/assets/img/easyBuy.png', Math.floor(80), Math.floor(445), Math.floor(110), Math.floor(15))
              ctx.setTextAlign('left') //设置文字要垂直居中

              ctx.setFillStyle('#333') //字体颜色
              ctx.setFontSize(10) //字体大小
              ctx.fillText(that.data.userInfo.username, Math.floor(80), Math.floor(410))
              ctx.fillText("华为全屋定制,共享购物时光", Math.floor(80), Math.floor(430))
              ctx.draw()
              //将画布转化成图片
              let timmm = setTimeout(() => {
                wx.canvasToTempFilePath({
                  canvasId: "myCanvas",
                  fileType: 'jpg',
                  success(daa) {
                    wx.hideLoading();
                    that.setData({
                      posterUrl: daa.tempFilePath,
                      show: true
                    })
                    clearTimeout(timmm)
                    wx.hideLoading()
                  },
                  fail(err) {
                    wx.hideLoading();
                    wx.showToast({
                      title: '生成错误，请重试！',
                      icon: 'none'
                    })
                    console.log(err)
                  }
                })
              }, 600)
            }
          },
          fail(err) {
            wx.hideLoading();
            app.$tip(err.msg);
          }
        })
      } else {
        app.$tip(res.msg);
      }
    })
  },

  //显示海报
  poster() {
    let urls = [];
    urls.push(this.data.posterUrl);
    console.log(this.data.posterUrl);
    wx.previewImage({
      current: urls[0],
      urls: urls,
    })
    this.setData({
      show: false
    })
  },
  detail(e) {
    // 未登陆
    if (!app.globalData.userId) {
      wx.showModal({
        title: '温馨提示',
        content: '您还未登录,请先登录!',
        confirmText: '去登录',
        confirmColor: '#57b127',
        success(res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/wxLogin/wxLogin',
            })
          } else if (res.cancel) {

          }
        }
      })
      return
    } else {
      wx.navigateTo({
        url: '/pages/article/article?id=' + e.currentTarget.dataset.id,
      })
    }
  },
  onPullDownRefresh: function () {
    this.setData({
      showit: true, // 是否显示
      show: false, // 显示分享弹窗？
      buynum: 0, // 下单人数
      invitenum: 0, // 邀请人数
      rules: null, // 规则
      posterUrl: null, // 绘制完成的海报
      imgURL: '', // 分享海报的商品图片
    })
    this.getData();
  },


  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    this.closed();
    if (res.from === 'button') {
      // 来自页面内转发按钮
      return {
        title: '华为全屋定制',
        path: '/pages/home/home?pid=' + JSON.parse(wx.getStorageSync('userInfos')).invitation_code
      }
    }
    return {
      title: '华为全屋定制',
      path: '/pages/home/home?pid=' + JSON.parse(wx.getStorageSync('userInfos')).invitation_code
    }
  }
})